package ru.jetsoft.reg112.desktop;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;

public abstract class BaseController implements Initializable {

    private Scene scene;
    private Stage stage;

    public void setScene(Scene scene) {
        this.scene = scene;
    }

    public Scene getScene() {
        return scene;
    }

    public Stage getStage() {
        return stage;
    }

    public void setStage(Stage stage) {
        this.stage = stage;
    }

    protected void fireMessage(ActionEvent event, String title, String message, Throwable th) {
        try {
            if(scene != null) {
                Stage stage = new Stage();
                String details = "";
                if(th != null) {
                    details = stackTraceToString(th);
                }
                FXMLLoader loader = new FXMLLoader(getClass().getResource("messagebox.fxml"));
                Parent root = (Parent) loader.load();
                MessageBoxController controller = (MessageBoxController) loader.getController();
                controller.setMessage(message);
//                MessageBox messageBox = new MessageBox(message, details);
                stage.setScene(new Scene(root));
                stage.setTitle(title);
                stage.initModality(Modality.WINDOW_MODAL);
                stage.initOwner(scene.getWindow());
                stage.show();
            }
        } catch(IOException ex) {
        }
    }

    public static String stackTraceToString(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        return sw.toString();
    }
}
